<template>
  <div class="article-list">
    <van-pull-refresh v-model="isLoading" :success-text="refreshSuccessText" success-duration="1000" @refresh="onRefresh">
      <van-list v-model="loading" :error.sync="error" error-text="请求失败，点击重新加载" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <!-- <van-cell v-for="(artical,index) in list" :key="index" :title="artical.title" /> -->
        <ArticleItem v-for="(article,index) in list" :key="index" :article="article"></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article.js'
import ArticleItem from '@/components/article-list/index.vue'
export default {
  name: 'ArticleList',
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isLoading: false,
      refreshSuccessText: '刷新成功'
    }
  },
  methods: {
    async onLoad() {
      // 1 请求获取数据
      // 2. 把请求结果数据放到 list 数组中
      // 3. 本次数据加载结束之后要把加载状态设置为结束
      // 4. 判断数据是否全部加载完成
      // 初始化或滚动到底部的时候会触发调用 onLoad
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now()
        })
        // console.log(data)
        const { results } = data.data
        // console.log(results)
        this.list = [...this.list, ...results]
        this.loading = false
        if (results.length) {
          // 证明数组里面还有数据， 获取下一个时间戳
          this.timestamp = data.data.pre_timestamp
        } else {
          // 数组里面没有数据了  所以把finished 设置为 true
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now()
        })
        // console.log(data)
        const { results } = data.data
        this.list = [...results, ...this.list]
        this.isLoading = false
        this.refreshSuccessText = `刷新成功 更新了${results.length}条数据`
      } catch (err) {
        // console.log('刷新失败', err)
        this.isLoading = false
        this.refreshSuccessText = '刷新失败'
      }
    }
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="less" scoped>
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
